package com.goldcn.sys.service;

import com.goldcn.common.CommonUtils;
import com.goldcn.jwt.JWTSigner;
import com.goldcn.sys.dao.GcnSysUserMapper;
import com.goldcn.sys.dto.LoginDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * redis服务
 * Created by Administrator on 2016/3/1.
 */

@Service("rService")
@Transactional
@ConfigurationProperties(prefix = "spring.redis")
public class RedisService {

    private static JWTSigner signer = new JWTSigner();
    private Long expire;
    private Long expireRas;
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    GcnSysUserMapper gcnSysUserMapper;
    /*@Autowired
    UserService userService;*/

    /**
     * token缓存并保存用户登录信息
     */
    public String addOrUpdate(Map<String,Object> userMap, LoginDto loginDto, String key) {
        if(CommonUtils.isEmpty(key)){
            key = userMap.get("userID")+"";
        }
        String token=signer.sign(userMap);
        redisTemplate.opsForValue().set(key,token);
        //缓存不超过1周
        if(loginDto.getExpireDate()>0&&loginDto.getExpireDate()<8) {
            int seconds=86400*loginDto.getExpireDate();
            redisTemplate.expire(key,seconds, TimeUnit.SECONDS);
        }
        else
            redisTemplate.expire(key,expire,TimeUnit.SECONDS);
        //userMapper.updateByPrimaryKeySelective(user);
        return token;
    }


    public String addOrUpdate(Map<String,Object> userMap, LoginDto loginDto) {
        return addOrUpdate(userMap,loginDto,null);
    }

  /*  public void set(){
        redisTemplate.opsForValue().set("9-NM0TXGTZmjyt6frmjC0A","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiI5LU5NMFRYR1RabWp5dDZmcm1qQzBBIiwidXNlck5hbWUiOiIxMzMxNjU4ODY4NyJ9./8Xjupyd284vH/DN/KrYkzEaULhrndfW36DRXBJUcvA=");
    }*/


    public Object loadKey(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public void delete(String userId) {
        redisTemplate.delete(userId);
    }


    /**
     * RAS私钥
     */
    public void addOrUpdateRAS(String rasID,Object privateKey){
        redisTemplate.opsForValue().set(rasID,privateKey);
        redisTemplate.expire(rasID,expireRas,TimeUnit.SECONDS);
    }

    public void addOrUpdateRAS(String rasID,Object privateKey,Long expireRas){
        redisTemplate.opsForValue().set(rasID,privateKey);
        redisTemplate.expire(rasID,expireRas,TimeUnit.SECONDS);
    }

    public void setExpire(Long expire) {
        this.expire = expire;
    }

    public void setExpireRas(Long expireRas) {
        this.expireRas = expireRas;
    }
}
